package com.kitty.record.kittyjava.juc;

import jdk.nashorn.internal.ir.Block;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列
 *
 *              Throws exception        Special value       Blocks              Times out
 * Insert       add(e)                  offer(e)            put(e)              offer(e, time, unit)
 * Remove       remove()                poll()              take()              poll(time, unit)
 * Examine      element()               peek()              not applicable      not applicable
 *
 *
 * @Author SHEN
 * @Date 2021/1/14
 */
public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        final BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        //one throws an exception队列满了就抛出异常
        /*System.out.println("queue.add(\"1\") = " + queue.add("1"));
        System.out.println("queue.add(\"2\") = " + queue.add("2"));
        System.out.println("queue.add(\"3\") = " + queue.add("3"));
        System.out.println("queue.element() = " + queue.element());
        queue.remove();
        System.out.println("queue.add(\"4\") = " + queue.add("4"));*/

        //the second returns a special value (either null or false, depending on the operation)；
        //当队列满了会返回特殊的值（true或者false）
        /*System.out.println("queue.offer(\"1\") = " + queue.offer("1"));
        System.out.println("queue.offer(\"2\") = " + queue.offer("2"));
        System.out.println("queue.offer(\"3\") = " + queue.offer("3"));
        System.out.println(queue.peek());
        queue.poll();
        System.out.println("queue.offer(\"4\") = " + queue.offer("4"));*/

        //the third blocks the current thread indefinitely until the operation can succeed
        //当队列满了会死死的等下去，直到成功为止
        /*queue.put("1");
        System.out.println("put(1)");
        queue.put("2");
        System.out.println("put(2)");
        queue.put("3");
        System.out.println("put(3)");
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("take");
                queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        queue.put("4");
        System.out.println("put(4)");*/


        //the fourth blocks for only a given maximum time limit before giving up
        //设置一个定时器在等待一定的时间后自动放弃
        queue.offer("1",2,TimeUnit.SECONDS);
        System.out.println("1");
        queue.offer("2",2,TimeUnit.SECONDS);
        System.out.println("2");
        queue.offer("3",2,TimeUnit.SECONDS);
        System.out.println("3");
        queue.offer("4",2,TimeUnit.SECONDS);
    }




}
